package com.wanli.storemobile.widget;

import android.app.Activity;
import android.app.Dialog;
import android.os.Build;
import android.view.View;
import android.widget.TextView;

import com.wanli.storemobile.R;


/**
 * @author FangHeQiang
 * @description:自定义网络加载框
 * @date :2019/8/28 14:08
 */
public class ViewLoading {
    private static Activity activity;

    public static void showProgress(Activity mActivity) {
        if (isDestroy(mActivity)) {
            return;
        }
        showProgress(mActivity, "加载中......");
    }


    private static Dialog progress;

    public static void showProgress(Activity mActivity, String message) {
        if (isDestroy(mActivity)) {
            return;
        }
        activity = mActivity;
        if (progress == null) {
            progress = new Dialog(mActivity, R.style.ShowProgressUtils);
        }
        View view = View.inflate(mActivity, R.layout.dialog_view_loading, null);
        TextView textView = view.findViewById(R.id.loadingText);
        textView.setText(message);
        progress.setContentView(view);
        progress.setCanceledOnTouchOutside(false);
        progress.setCancelable(false);
        if (!isDestroy(mActivity) && !isShowing()) {
            try {
                progress.show();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public static void dismissProgress() {
        if (progress != null && !isDestroy(activity) && isShowing()) {
            activity.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    try {
                        progress.dismiss();
                        progress = null;
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });
        }
    }

    public static boolean isShowing() {
        if (progress != null) {
            return progress.isShowing();
        }
        return false;
    }

    public static boolean isDestroy(Activity mActivity) {
        boolean isDestroy = false;
        if (mActivity == null || mActivity.isFinishing()) {
            isDestroy = true;
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            if (mActivity == null || mActivity.isFinishing() || mActivity.isDestroyed()) {
                isDestroy = true;
            }
        }
        return isDestroy;
    }
}
